var express = require('express');
const stulend = express.Router();
var bodyParser = require('body-parser');
const path = require("path");
const Database = require("better-sqlite3");
//获取数据库中管理员账号密码等信息
const mydb = new Database(path.resolve(__dirname, "../database/infor.db"), { verbose: console.log });

// 创建 application/x-www-form-urlencoded 编码解析
stulend.use(bodyParser.urlencoded({ extended: false }))
stulend.use(express.json());
stulend.use(bodyParser.json());

stulend.post('/stulend', function (req, res) {
    // 获取前端数据
    var response = {
        "stu_id": req.body.stu_id,
        "code": req.body.code
    };
    // console.log(response);
    //指定数据库文件路径
    const get_user_by_id = mydb.prepare('SELECT * FROM student WHERE stu_id= ?');//一个查询语句对象
    var a = get_user_by_id.get(response.stu_id);//执行查询
    // console.log(a);
    if (a) {
        // 如果查询到了说明此同学存在
        // 查询条形码是否输入错误
        const get_user_by_id2 = mydb.prepare('SELECT * FROM book WHERE code= ? and logoff=?');//书籍要存在
        var b = get_user_by_id2.get(response.code, "no");//执行查询
        if (b) {
            // 如果书存在
            console.log("存在此图书");
            // 判断借阅图书数量是否足够
            if (b.inventory >= 1) {
                //可借阅数量足够
                // 开始借阅图书
                // 先要查询该同学是否有欠款
                const fine = mydb.prepare('SELECT * FROM fine WHERE stuid= ?');//一个查询语句对象
                var c = fine.get(response.stu_id);//执行查询
                if (c) {
                    console.log("有欠款");
                    // 如果有欠款，跳转到处理欠款的页面
                    res.sendFile(path.resolve(__dirname, "../public/html/fine.html"));
                }
                else {
                    console.log("无欠款");
                    // 先找到lend中最后一条的记录
                    const lend_last = mydb.prepare('SELECT * FROM lend order by lend_num desc limit 0,1');//一个查询语句对象
                    var d = lend_last.get();//执行查询
                    // console.log(d);
                    var new_len_num = d.lend_num + 1;// 最新一条记录的编号

                    // 获取当前时间---lendtime
                    var date = new Date();
                    var year = date.getFullYear(); //获取当前年份
                    var mon = date.getMonth() + 1; //获取当前月份
                    var da = date.getDate(); //获取当前日
                    var newmon = mon;
                    if (mon > 0 & mon < 10) {
                        mon = "0" + mon;
                    }
                    if (da > 0 & da < 10) {
                        da = "0" + da;
                    }
                    var nowtime = year + "-" + mon + "-" + da;
                    // 借阅到期时间---due 在lendtime的基础上加 1 个月
                    if (newmon == 12) {
                        newmon = parseInt(newmon + 1) / 12;
                    }
                    if (newmon > 0 & newmon < 10) {
                        newmon = "0" + (newmon + 1);
                    }
                    var duetime = year + "-" + newmon + "-" + da;
                    console.log("nowtime: " + nowtime);
                    console.log("duetime: " + duetime);
                    console.log(new_len_num);
                    //插入一条记录
                    // 无欠款，可以借书，在 lend 表中插入数据
                    const insert_lend = mydb.prepare('INSERT INTO lend (lend_num,code,stuid,lendtime,due,state) VALUES (@lend_num,@code,@stuid,@lendtime,@due,@state)');
                    insert_lend.run({ lend_num: new_len_num, code: response.code, stuid: response.stu_id, lendtime: nowtime, due: duetime, state: "no" });
                    // 同时 book 表中的现存量 - 1
                    const updata_book1 = mydb.prepare('UPDATE book SET inventory =inventory-1  WHERE code=@code');
                    updata_book1.run({ code: response.code });
                    // 以及 book 表 借阅次数+1
                    const updata_book2 = mydb.prepare('UPDATE book SET borrownum =borrownum+1  WHERE code=@code');
                    updata_book2.run({ code: response.code });
                    res.sendFile(path.resolve(__dirname, "../public/html/lend_success.html"));
                }
            }
            else {
                // 可借阅数量不足
                console.log("可借阅数量不足");
                res.sendFile(path.resolve(__dirname, "../public/html/inadequate.html"));
            }
        }
        else {
            // 书籍不存在
            console.log("书籍不存在");
            res.sendFile(path.resolve(__dirname, "../public/html/lend_error.html"));
        }
    }
    else {
        // 如果没有查询到，说明该同学不存在
        console.log("该同学不存在");
        res.sendFile(path.resolve(__dirname, "../public/html/stu_error.html"));
    }
});

module.exports = stulend;